
capture program drop causal_2sls_est
program define causal_2sls_est
matrix IV =J(4,16,.)

**(2.1) TE custom bootstrap
use "${causal_bt_dir}/BT_est_${density}_reg${reg_degree}_${fe_status}_${cutoff}_${firm_name}_${name}_${year_name}_trade_custom_degree${degree}_${low}_${high}_bin${binname}_in${zoom_in_c300}_out${zoom_out_c300}.dta", clear
keep  ITT_cp_*
forvalues ii=1 (1) $nboot {
rename ITT_cp_`ii'   ITT_cp_trade_`ii'
}
gen id=1
save "${causal_bt_dir}/BT_custom_for_IV", replace  


**(2.2) TE y & IV bootstrap
use "${causal_bt_dir}/BT_est_${density}_reg${reg_degree}_${fe_status}_${cutoff}_${firm_name}_${name}_${year_name}_${myvar}_degree${degree}_${low}_${high}_bin${binname}_in${zoom_in_c300}_out${zoom_out_c300}.dta", clear
gen id=1
qui merge 1:1 id using   "${causal_bt_dir}/BT_custom_for_IV"
forvalues ii=1 (1) $nboot {
gen IV_`ii'=ITT_cp_`ii'/ ITT_cp_trade_`ii'
}
keep IV_*
keep if _n==1
xpose, clear 
sort v1 
qui su v1, detail 
global X_se= r(sd)

matrix IV[2,2]=${X_se}

svmat IV
keep IV*
rename IV1 varname
rename IV2 IV
rename IV3 t
keep varname IV t 
tostring varname, replace
replace varname="${myvar}" if _n==1
replace varname=""    if _n==2
keep if _n<=2

end

